﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using Website.Logger;
using System.Drawing;
using DAL;
using BOL;
using WebLib;
using System.Web.Script.Services;
using System.Web.Services;
using UtilityExtensions;


namespace UILGestion.Control
{
    public partial class ECOCPanel : System.Web.UI.UserControl
    {

        public ECOCPanel()
        {
            ecBol = new EstructuraCostoBL();
        }
        public event EventHandler DataBound;
        public ListView ListView
        {

            get { return ListView1; }

        }


        public List<int> SeleccionList
        {
            get
            {
                // Create a List to hold the EmployeeID values to delete
                List<Int32> idLista = new List<Int32>();

                // Iterate through the Employees.Rows property
                foreach (ListViewDataItem row in ListView1.Items)
                {

                    // Access the CheckBox
                    CheckBox cb = (CheckBox)(row.FindControl("chkEmployeeSelector"));
                    if (cb != null && cb.Checked)
                    {
                        // Save the EmployeeID value for deletion
                        // First, get the EmployeeID for the selected row
                        
                        int idInternal = int.Parse(ListView1.DataKeys[row.DisplayIndex][0].ToString());

                        idLista.Add(idInternal);
                    }
                }
                return idLista;
            }
        }
        public int pagesize { get { return Util.GetPageSizeCookie(); } }
       
        
        protected void ListView1_DataBound(object sender, EventArgs e)
        {
            if (DataBound != null)
                DataBound(sender, e);
        }
        protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                //var link = e.Item.FindControl("HyperLink1") as HyperLink;
                //var r = e.Item as ListViewDataItem;
                //// var d = r.DataItem as OrdenCompraListInfo;
                ////link.NavigateUrl ="javascript:PageMethods.ToggleTag({0},'{1}',ToggleTagCallback)".Fmt(d.idInternal, link.ClientID);


            }

        }

        private EstructuraCostoBL ecBol;

     

     


        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                

                if (!this.IsPostBack)
                {
                    idObra.Value = (string)Request.QueryString["idObra"];
                  
                    FormatForm();

                }
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

            //FormatForm();

        }
      
        public void LoadRecurso(int idEstructuraCosto,
                                string estructuraCostoStr,
                                int idProveedor,
                                string ProveedorStr,
                                int idMoneda,
                                string monedaStr,
                                string idListYaUtilizado,
                                string orden=default(string))
        {
            try
            {
                

                List<ComparativoItemInfo> ds = (List<ComparativoItemInfo>)System.Web.HttpContext.Current.Session[idListYaUtilizado];
                if (ds == null)
                {
                    ds = new List<ComparativoItemInfo>();
                }

                monedaLBL.Text = monedaStr;
                proveedorLBL.Text = ProveedorStr;
                this.idEstructuraCosto.Value = idEstructuraCosto.ToString();
                this.estructuraCostoLBL.Text = estructuraCostoStr;
                IEnumerable<int> itemYaUtilizado = ds.Select(p => p.idEstructuraCostoItem);


                List<EstructuraCostoItemConfInfo> q =
                  this.ecBol.getEstructuraCostoItemConfigDisp(
                   idEstructuraCosto,
                  idMoneda,
                  itemYaUtilizado,
                  0,
                  150,
                  orden);
                //-----------agrupamos  segun ordenCompra
                // tomamos todos las ordenes de compra
                //debe de restar los que ya se encuentran utilizados
  
                Session[idRecursoOCList.Value.ToString()] = ecBol.getECItemConfigDispAGRPOC(q,
                                                                                          idProveedor);
               
                BindDataOCItem();
                //setEstadistica();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        private void FormatForm()
        {


            
            idRecursoOCList.Value = Parametros.GenerarID().ToString();

            List<EstructuraCostoItemConfInfo> itemList2 = new List<EstructuraCostoItemConfInfo>();
            List<OrdenCompraListInfo> itemList1 = new List<OrdenCompraListInfo>();
            
            Session[idRecursoOCList.Value.ToString()] = itemList1;
         
        }

      

      
        //private void setEstadistica()
        //{
        //    List<EstructuraCostoItemConfInfo> itema = this.ItemLista;

            
        //    TotalLabel.Text = String.Format("{0} {1:N}", simbolMoneda.Value, itema.Sum(p => p.totalDisp));
        //    totalUpdatePanel.Update();

        //}
      

        private void BindDataOCItem()
        {

            List<OrdenCompraListInfo> item =
                (List<OrdenCompraListInfo>)Session[idRecursoOCList.Value.ToString()];


            ListView1.DataSource = item;
            ListView1.DataBind();
            //ListView1.Update();


        }


    

        protected void ItemAllSelectChange(object sender, EventArgs e)
        {
            //solo los seleccionados
            //seleccionamos todos los  item
            //foreach (GridViewRow row in ListView1.Rows)
            //{
            //    CheckBox cb = (CheckBox)(row.FindControl("chkEmployeeSelector"));
            //    cb.Checked = ((CheckBox)sender).Checked;
            //}
            //UpdatePanelGrilla.Update();
            //setEstadistica();

        }
        protected void ItemSelectChange(object sender, EventArgs e)
        {
            //solo los seleccionados
            //seleccionamos todos los  item
                       
            //setEstadistica();

        }
        protected string GetSortDirection(string column)
        {

            // By default, set the sort direction to ascending.
            string sortDirection = "ASC";

            // Retrieve the last column that was sorted.

            string sortExpression = ViewState["SortExpression"] as string;

            if (sortExpression != null)
            {
                // Check if the same column is being sorted.
                // Otherwise, the default value can be returned.
                if (sortExpression == column)
                {
                    string lastDirection = ViewState["SortDirection"] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }

            // Save new values in ViewState.
            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;

            return sortDirection;
        }

     

        protected void estructuraDDL_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                //if (((DropDownList)sender).Items.Count > 0)
                //{
                //    // cargamos las estructuras de costo necesarias 
                //    idEstructuraCosto.Value = ((DropDownList)sender).SelectedValue;
                //    if (idEstructuraCosto.Value != "0")
                //    {
                //        loadProveedor();
                //        LoadRecurso(this.idMoneda, 
                //                    this.idListYaUtilizados.Value);
                        

                //      }
                   
                //}
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }
        }

       
    }
}